package com.da.javatest.interview.other.print;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chenlida
 * @date 2020/10/20 14:52
 * @description
 */
public class PrintABC2 {
    private int times;
    private int state;
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public PrintABC2(int times) {
        this.times = times;
    }

    private void print(String msg, int targetState, Condition current, Condition next) {
        for (int i = 0; i < times; ) {
            lock.lock();
            try {
                while (state % 3 != targetState) {
                    current.await();
                }
                i++;
                state++;
                System.out.print(msg);
                next.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public void printA() {
        print("A", 0, c1, c2);
    }

    public void printB() {
        print("B", 1, c2, c3);
    }

    public void printC() {
        print("C", 2, c3, c1);
    }

    public static void main(String[] args) {
        PrintABC2 printABC1 = new PrintABC2(10);
        new Thread(printABC1::printA).start();
        new Thread(printABC1::printB).start();
        new Thread(printABC1::printC).start();
    }
}
